package end.ser.realm;

import java.util.Collection;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;

import redis.clients.jedis.Jedis;
import end.bean.shiro.Manager;
import end.bean.shiro.Role;
import end.constant.Const;
import end.controller.AlbumForController;
import end.ser.ManagerSER;
import end.util.AESUtils;
import end.util.MD5Utils;
import end.util.export.excel.DateUtils;
import end.util.jedis.JedisPoolUtils;

/**
 * 
 * MyRealm.java 2016-7-9
 * 
 * Copyright zhaocj Inc. All rights reserved. Love Me Like Love Justin Bieber
 */
@Service
public class MyRealm extends AuthorizingRealm {
	private final static Logger log = LogManager
			.getLogger(AlbumForController.class);
	private ObjectMapper mapper = new ObjectMapper();
	@Autowired
	private ManagerSER<Manager> managerSER;

	public ManagerSER<Manager> getManagerSER() {
		return managerSER;
	}

	public void setManagerSER(ManagerSER<Manager> managerSER) {
		this.managerSER = managerSER;
	}

	/**
	 * 获取授权信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principalCollection) {
		// 获取登录时输入的用户名
		String loginName = (String) principalCollection.fromRealm(getName())
				.iterator().next();
		// 到数据库获取此用户
		Manager manager = null;
		try {
			manager = managerSER.selectByPrimaryKey(loginName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (manager != null) {
			// 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			// 用户的角色集合
			info.setRoles(manager.getRolesName());
			// 用户的角色对应的所有权限，如果只使用角色定义访问权限
			Collection<Role> roleList = manager.getRoles();
			for (Role role : roleList) {
				info.addStringPermissions(role.getPermissionsName());
			}
			return info;
		}
		return null;
	}

	/**
	 * 获取身份验证相关信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authenticationToken)
			throws AuthenticationException {
		// UsernamePasswordToken对象用来存放提交的登录信息
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		Manager manager = null;
		try {
			manager = managerSER.selectByPrimaryKey(token.getUsername());
			if (manager != null) {
				String saltStr = AESUtils.aesDecrypt(manager.getSalt(),
						AESUtils.SALTKEY);
				String codePassword = MD5Utils.GetSaltCode(
						String.valueOf(token.getPassword()), saltStr);
				if (manager.getPassword().equals(codePassword)) {
					manager.setLoginTime(DateUtils
							.getDate("yyyy-MM-dd HH:mm:ss"));
					manager.setLoginIP(SecurityUtils.getSubject().getSession()
							.getHost());
					// 将近期的登陆的管理元放入队列
					Jedis jedis = JedisPoolUtils.getJedis();
					jedis.select(6);
					jedis.lpush(Const.CURRENT_LOGIN_MANAGERS,
							mapper.writeValueAsString(manager));
					JedisPoolUtils.close(jedis);
					SecurityUtils.getSubject().getSession()
							.setAttribute(Const.SESSION_USER, manager);
					return new SimpleAuthenticationInfo(manager.getCode(),
							String.valueOf(token.getPassword()), getName());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}